<template>
  <div class="app-container">
    <Find :OriginalFilter="{ static: true }" :formList="formList" @findClicked="findClicked" @Launchform="Launchform"
      @clickNumber="clickNumber" />

    <div class="container">
      <el-card class="containerCard" shadow="always" :body-style="{ padding: '5' }">
        <div class="containerCardMain">
          <!-- 左 -->
          <div class="containerCardLeft">
            <!-- 左 -->
            <div class="containerCardLeftL">
              <h1 class="containerCardLeftLH1" style="margin: 0 10px">{{ $t(`Print.SelectInstruction`) }}</h1>
              <Table :tableData="TableData" :tableHeader="tableHeader" :TableHeight="100" :outTableHeight="90"
                @currentRow="clicktogetdata" :isLoading="isLoading" />
            </div>
            <!-- 右 -->
            <div class="containerCardLeftR">
              <h1 class="containerCardLeftLH1" style="margin: 0 10px">{{ $t(`Print.SelectATurn`) }}</h1>
              <Table :tableData="TableData1" :tableHeader="tableHeader2" :TableHeight="100" :outTableHeight="90"
                @currentRow="clicktogetdataT" :isLoading="isLoading1" />
            </div>
          </div>

          <!-- 右 -->
          <div class="containerCardRight" style="width: 82%">
            <Table :tableData="tableData" :summaryData="summaryData" :tableHeader="tableHeader3" summary
              :TableHeight="98" :isLoading="isLoading2" :cellClassName="cellClassName" />
          </div>
        </div>

        <PageModule :PageData="{ total }" @pageChange="handleSizeChange" @pageSizeChange="handleCurrentChange" />
      </el-card>
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import JMessage from '@/utils/JMessage'
export default defineComponent({
  name: 'DiscretionaryAccounts'
})
</script>
<script lang="ts" setup>
import { i18n, Jzhcn } from '@/i18n'
import { watch, ref, onMounted } from 'vue'
import { InstructAllocationAnd, CycleData, SubjectData, DropDownData } from '@/api/GeneralManager/Factoryinquiry/DiscretionaryAccounts'
import type {
  CommandParameter,
  AllocationOfAccountsDto,
  SubjectDataParameter,
  TableMainDto
} from '@/api/GeneralManager/Factoryinquiry/DiscretionaryAccounts'

const formList = ref([
  {
    type: 'input',
    inputPlaceholder: '请输入指令',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入型体',
    inputValue: ''
  },
  {
    type: 'select',
    selectValue: '',
    selectLabel: '部门',
    selectOptions: []
  },
  {
    type: 'radio',
    checkboxLabel: '收料状况',
    checked: true,
    label: '1'
  },
  {
    type: 'radio',
    checkboxLabel: '发料状况',
    checked: false,
    label: '2'
  },
  {
    type: 'radio',
    checkboxLabel: '库存状况',
    checked: false,
    label: '3'
  },
  {
    type: 'button',
    checkboxLabel: '置空',
    bgColor: '#1890FF'
  }
  // {
  //   type: 'input1',
  //   inputPlaceholder: '型体',
  //   inputValue: '',
  //   inputDisabled: true
  // },
  // {
  //   type: 'input1',
  //   inputPlaceholder: '型体颜色',
  //   inputValue: '',
  //   inputDisabled: true
  // },
  // {
  //   type: 'input1',
  //   inputPlaceholder: '型体数量',
  //   inputValue: '',
  //   inputDisabled: true
  // },
])

const isLoading = ref(true)

const isLoading1 = ref(true)

const isLoading2 = ref(true)

const TableThree = ref<TableMainDto[]>([])

const EvaluatesTheArrayReturnValue = (ArrayList: any) => {
  return ArrayList.map((item: any, index: any) => {
    return {
      optionKey: index,
      optionValue: item,
      optionLabel: item
    }
  })
}

const HeaderFind = async () => {
  const result = await DropDownData()
  const arrayResult = Object.keys(result).map((key) => ({ label: key, value: result[key] }))

  let NewArray = arrayResult.reduce<any>((arr, item) => {
    if (item.label && item.value) {
      // 只添加非空的 typeName 和 typeNo
      arr.push(item.label + ' ' + item.value)
    }
    return arr
  }, [])

  formList.value[2].selectOptions = EvaluatesTheArrayReturnValue(NewArray)
  formList.value[2].selectValue = NewArray[0]
}

// 选择指令表格数据
const TableData = ref<any[]>()

// 选择轮次表格数据
const TableData1 = ref<any>([])

// 总数
const total = ref<number>(0)

const lotNoO = ref<string>('')

const clicktogetdata = (row: any) => {
  const { lotNo } = row || {}
  isLoading2.value = true
  BodyTableParameter.value.lotNo = lotNo
  lotNoO.value = lotNo
  GetDepartmentData()
}

const clicktogetdataT = (row?: any) => {
  const { lsNo } = row || {}
  BodyTableParameter.value.lsNo = lsNo
  BodyTableParameter.value.style = BodyTableParameterList.value.style

  SubjectTableData()
}

const BodyTableParameter = ref<any>({
  lotNo: '',
  lsNo: 0,
  mtlCode: '1',
  processCode: '01',
  style: ''
})

interface summaryDataType {
  index: number
  num: number | undefined
}

// 计算金额总数
const summaryData = ref<summaryDataType[]>()

const SubjectTableData = async () => {
  isLoading2.value = true

  const result = await SubjectData(BodyTableParameter.value)

  if (result !== null) {
    TableThree.value = result.dto
  }

  if (result === null || result.data === null) {
    tableData.value = []
  } else if (result !== null && result.data !== null) {
    const supportTotal = result.dto[0].qty

    // 获取 supportTotal 中除 total 以外的键，并将它们按升序排列
    const supportKeys = Object.keys(supportTotal)
      .filter((key) => key !== 'total')
      .map((key) => parseFloat(key))
      .filter((key) => !isNaN(key))
      .sort((a, b) => a - b)

    // 根据索引数组生成 summaryData
    const summaryDataValue = supportKeys.map((key, index) => ({
      index: index === 0 ? 2 : index + 3, // 使用 index + 3 来保持递增索引
      num: supportTotal[key.toString()]
    }))

    // 对大于2的 index 进行减法操作
    summaryDataValue.forEach((item) => {
      if (item.index === 4 || item.index > 4) {
        item.index = item.index + 2
      } else {
        item.index = 5
      }
    })

    // 将 total 键对应的值放到下标为2的元素
    summaryDataValue.splice(1, 0, {
      index: 2,
      num: supportTotal.total
    })

    // 将 summaryData 值设置为生成的数组
    summaryData.value = summaryDataValue

    // 清空动态表头数据
    tableHeader3.value = []

    // 添加固定的列到表头
    tableHeader3.value.push(
      {
        label: 'Table.parts',
        prop: 'partName',
        width: '112px',
        backgroundColor: true
      },
      {
        label: 'Table.CutTimes',
        prop: 'cutSeq',
        width: '112px'
      },
      {
        label: 'Table.Total (outstanding/completed)',
        prop: 'total',
        width: '112px'
      },
      {
        label: 'Table.DispatchDate',
        prop: 'workDate',
        width: '112px'
      },
      {
        label: 'Table.CollectionDate',
        prop: 'collectDate',
        width: '112px'
      }
    )

    // 动态构建表头数据
    const allQtyArrays = result.dto.map((item: any) => {
      // 检查 item.qty 是否存在且不是 null
      if (item.qty !== null && typeof item.qty === 'object') {
        return Object.entries(item.qty).map(([size, value]) => ({ size, value }))
      } else {
        // 如果 item.qty 是 undefined 或 null，返回一个空数组
        return []
      }
    })

    allQtyArrays.forEach((item: any) => {
      item.forEach((item1: any) => {
        const existingColumn = tableHeader3.value.find((column: any) => column.prop === item1.size)
        if (!existingColumn) {
          tableHeader3.value.push({
            label: item1.size,
            prop: item1.size,
            backgroundColor: true,
            backgroundColor2: true,
            backgroundColor3: true
          })
        }
      })
    })

    // 将动态生成的列与表体数据进行映射
    TableThree.value.forEach((row) => {
      allQtyArrays.forEach((item: any) => {
        item.forEach((item1: any) => {
          const sizeProp = item1.size as keyof typeof row // 使用类型断言
            ; (row[sizeProp] as any) = row.qty[item1.size] || '' // 将qty中的值赋给相应的动态列
        })
      })
    })

    function calculateRangeTotal(item: any, start: any, end: any) {
      let total = 0
      let total1 = 0
      for (let key in item) {
        if (parseInt(key) >= start && parseInt(key) <= end) {
          const values = item[key].split('/')
          total += parseInt(values[0])
          total1 += parseInt(values[1])
        }
      }
      return `${total}/${total1}`
    }

    let start = 0 // 定义起始范围
    let end = 500 // 定义结束范围

    tableData.value = TableThree.value.map((item: any) => {
      item.total = calculateRangeTotal(item, start, end)
      item.partName = item.partName.value
      return item
    })
  }
  isLoading2.value = false
  ChangeColorF()
}

//______________________________________________________________________________
let RowMap = new Map() //要高亮列数
const ChangeColorF = () => {
  //清空之前的高亮
  RowMap.clear()
  // 获取要高亮的列
  Object.values(TableThree.value).forEach((i) => {
    Object.values(i.qty).forEach((i0: any, k0: number) => {
      const [val0, val1] = i0.split('/').map(Number)
      if (val0 === 0) {
        RowMap.set(i0, 'G')
      } else if (val0 !== 0 && val1 !== 0) {
        RowMap.set(i0, 'H')
      } else {
        RowMap.set(i0, 'Null')
      }
    })
  })
}
//监厅
const cellClassName = ({ row, column, rowIndex, columnIndex }: any) => {
  const cellValue = row[column.property]
  if (RowMap.has(cellValue)) {
    if (RowMap.get(cellValue) === 'G') {
      if (RowMap.get(rowIndex) === 'CZ') {
        return 'highGreen'
      } else {
        RowMap.set(rowIndex, 'CG')
        return 'highGreen'
      }
    }
    if (RowMap.get(cellValue) === 'H') {
      RowMap.set(rowIndex, 'CZ')
      return 'highGwarning'
    }
  }
  if (columnIndex === 0 && RowMap.has(rowIndex)) {
    if (RowMap.get(rowIndex) === 'CG') return 'highGreen'
    if (RowMap.get(rowIndex) === 'CZ') return 'highzi'
    return ''
  }
}

// 需要收集的数据
const dataCollection = ref<CommandParameter>({
  lotNo: '',
  pageNum: 1,
  pageSize: 40,
  style: ''
})

// 选择指令数据
const ConsumableTableData = async () => {
  isLoading.value = true
  const result = await InstructAllocationAnd(dataCollection.value)
  TableData.value = result.dto.map((item: any) => {
    return { lotNo: item }
  })
  total.value = result.total
  isLoading.value = false
  // 使用短路逻辑处理可能为 undefined 的属性
  lotNoO.value = TableData.value[0]?.lotNo || ''
  BodyTableParameter.value.lotNo = TableData.value[0]?.lotNo || ''
  BodyTableParameter.value.lotNo = TableData.value[0]?.lotNo || ''
  if (BodyTableParameter.value.lotNo !== '') {
    GetDepartmentData()
  }
}

// 轮次
const BodyTableParameterList = ref()

const GetDepartmentData = async () => {
  const result = await CycleData(lotNoO.value)
  if (result.lsNo !== null && result.lsNo.length !== 0) {
    TableData1.value = result.lsNo.map((item: any) => {
      return { lsNo: item }
    })
  }

  if (TableData1.value.length !== 0) {
    BodyTableParameter.value.lsNo = TableData1.value[0].lsNo
  } else {
    BodyTableParameter.value.lsNo = ''
  }

  if (result.detail.length !== 0) {
    BodyTableParameterList.value = result.detail
    BodyTableParameter.value.style = result.detail.style
  } else {
    BodyTableParameter.value.style = ''
  }

  isLoading1.value = false
  SubjectTableData()
}

// 统一调用接口
const interAceFunct = () => {
  // 选择指令数据
  // ConsumableTableData()

  // 部门下拉框数据
  HeaderFind()
}

onMounted(() => {
  interAceFunct()
})

const tableData = ref()

const tableHeader = ref([
  {
    label: '指令',
    prop: 'lotNo'
  }
])

const tableHeader2 = ref([
  {
    label: '轮次',
    prop: 'lsNo',
    width: '112px'
  }
])

const tableHeader3 = ref<any>([
  {
    label: '部位',
    prop: 'partName1',
    width: '112px'
  },
  {
    label: '裁次',
    prop: 'cutSeq',
    width: '60'
  },
  {
    label: '合计(欠数/已制)',
    prop: 'total',
    width: '112px'
  },
  {
    label: '派工日期',
    prop: 'workDate',
    width: '80'
  },
  {
    label: '采集日期',
    prop: 'collectDate',
    width: '80'
  }
])

const handleSizeChange = (val: number) => {
  dataCollection.value.pageNum = val
  ConsumableTableData()
}
const handleCurrentChange = (val: number) => {
  dataCollection.value.pageSize = val
  ConsumableTableData()
}

const Launchform = (val: any) => {
  dataCollection.value.lotNo = val[0].inputValue
  dataCollection.value.style = val[1].inputValue
  BodyTableParameter.value.processCode = val[2].selectValue.split(' ')[1]
  ConsumableTableData()
}

const findClicked = (find: any) => {
  if (find === '置空') {
    clearFormList1()
  }
}

const clearFormList1 = () => {
  formList.value.forEach((item) => {
    if (item.type === 'input') {
      item.inputValue = ''
    }
  })
}

const clickNumber = (val: any) => {
  BodyTableParameter.value.mtlCode = val
  SubjectTableData()
}
</script>

<style lang="less" scoped>
.container {
  margin-top: 12px;
}

.containerCardLeft {
  display: flex;
}

// 卡片
.containerCard {
  box-shadow: none;

  .containerCardMain {
    display: flex;
  }
}

.containerCardRight {
  margin-left: 30px;
  margin-top: 20px;
}

.containerCardLeftR {
  margin-left: 30px;
}

h1 {
  font-size: 16px;
}

:deep(.highGreen) {
  background-color: #41d477 !important;
  color: black;
}

:deep(.highGwarning) {
  background-color: #f0f042 !important;
  color: black;
}

:deep(.highzi) {
  background-color: #ff80ed !important;
  color: black;
}
</style>
